import json
import os
import time
import threading
import socket
import datetime
import ssl
import struct
import makeRedis
import numpy as np


def dns():
    os.system('sudo python3 dns.py')


def execve():
    os.system('sudo python3 execve.py')


def tcp():
    os.system('sudo python3 tcp4.py')


class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, bytes):
            return str(obj, encoding='utf-8')
        return json.JSONEncoder.default(self, obj)


def keep_alive():
    so = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = "127.0.0.1"
    port = 8887
    CA_FILE = "/home/a/ou/key/ca.crt"
    KEY_FILE = "/home/a/ou/key/client.key"
    CERT_FILE = "/home/a/ou/key/client.crt"
    cron = '/etc/crontab'
    context = ssl.SSLContext(ssl.PROTOCOL_TLS)
    context.check_hostname = False
    context.load_cert_chain(certfile=CERT_FILE, keyfile=KEY_FILE)
    context.load_verify_locations(CA_FILE)
    context.verify_mode = ssl.CERT_REQUIRED
    sock = context.wrap_socket(so, server_side=False)
    sock.connect((host, port))
    makeRedis.addip()
    makeRedis.dns()
    while 1:
        now = datetime.datetime.now().strftime('%Y-%m-%d  %H:%M:%S')
        temp = open(cron, 'r', encoding='utf-8').read()
        alive = {'type': 'keep_alive', 'time': now, 'cron': temp}
        keep = json.dumps(alive, cls=MyEncoder, indent=4).encode()
        data = struct.pack("I%ds" % (len(keep),), len(keep), keep)
        sock.send(data)
        time.sleep(60)


if __name__ == '__main__':
    # t1 = threading.Thread(target=dns)
    # t2 = threading.Thread(target=execve)
    # t3 = threading.Thread(target=tcp)
    # t4 = threading.Thread(target=keep_alive)
    # t1.start()
    # t2.start()
    # t3.start()
    # t4.start()
    # t1.join()
    # t2.join()
    # t3.join()
    # t4.join()
    keep_alive()
# import re
#
# line = "<DNS Question: 'autoconfig.thunderbird.net.' qtype=AAAA qclass=IN>";
#
# searchObj = re.search(r'<DNS Question: (.*?) .*', line, re.M | re.I).group(1)
#
# obj = searchObj
#
# if searchObj:
#     print(searchObj)
#     print(obj)
# else:
#     print("Nothing found!!")
# class test:
#     def __init__(self, size, type, data):
#         self.size = size
#         self.type = type
#         self.data = data
#
#     # def make(self, size, type, data):
#     #     return self.test(size, type, data)
#
#
# a = test(16, 1, {'kk': 11, 'ere': 23})
# k = {'kk': 11, 'ere': 23}
# t = json.dumps(k)
# q = t.encode()
# print(type(q))
